###################################################
# Data Imputation
###################################################
rm(list=ls(all=TRUE))
#install.packages("Amelia")
library(Amelia)
#install.packages("readstata13")
library(readstata13)
#install.packages("Hmisc")
library(Hmisc)

# set working directory
us_capex <- read.dta13("us-capex-imputation.dta")

head(us_capex)
# Generate 10 imputed datasets 
set.seed(231011); imputation.us <- amelia(us_capex,m=10,ts="year",cs="country",polytime=3)
write.amelia(obj=imputation.us,file.stem="us_capex",row.names=F)


################################################################################
#Run do file -- capex_usfdi.do
# Retrieve coef estimates for each imputated dataset
#################################################################################
# Combine 10 sets of estimated coefficients
###########
coef.us <- read.dta13("us_capex_coefs.dta")
us.coefs <- coef.us[,c(1,2)]
us.coefs$id <- rep(1:10, each = 15)  
us.coefs <- reshape(us.coefs,timevar = "var",idvar="id",direction = "wide")
us.coefs <- us.coefs[,-1]

us.se <- coef.us[,c(1,3)]
us.se$id <- rep(1:10,each=15)   
us.se <- reshape(us.se,timevar = "var",idvar="id",direction = "wide")
us.se <- us.se[,-1]
us.result <- mi.meld(q = us.coefs, se = us.se)

out.us<-matrix(cbind(us.result$q.mi, us.result$se.mi, us.result$q.mi/us.result$se.mi),15,3 )
colnames(out.us)=c("Coef", "SE", "Z")
rownames(out.us)<-unique(coef.us[,1])
print(out.us)
write.csv(out.us,file = "results_us_capex.csv",row.names = T)


